# -*- coding: utf-8 -*-

'''多线程获取Figure的json数据'''

import threading
import urllib2
import time
import os

class FigureImageThread(threading.Thread):
    def __init__(self, image_url_queue):
        threading.Thread.__init__(self)
        self.image_url_queue = image_url_queue
        
    '''保存分类图片'''
    def saveCategoryImage(self, image_id, image_src):
        save_file = 'image/figure/' + image_id + '.jpg'
        if os.path.isfile(save_file):
            return
        while True:
            url = 'https://app.figure1.com' + image_src
            req = urllib2.Request(url)
            
            #print url
            
            req.add_header('Host', 'app.figure1.com')
            req.add_header('User-Agent', 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36')
            req.add_header('Referer', 'https://app.figure1.com/login')
            req.add_header('Connection', 'keep-alive')
            req.add_header('X-Requested-With', 'XMLHttpRequest')
            req.add_header('Content-Type', 'application/x-www-form-urlencoded')
            
            try:
                figure_image = urllib2.urlopen(req).read()
            except:
                figure_image = None
            
            if figure_image is None or len(figure_image) == 0:
                print 'sleep 0.1-----'
                time.sleep(0.1)
            else:
                break
            
        
        img = open(save_file, "wb")
        img.write(figure_image)
        img.close()

    def run(self):
        while True:
            image_id_url = self.image_url_queue.get()
            #print image_id_url
            image_id = str(image_id_url[0])
            image_url = str(image_id_url[1])
            #print "开始下载图片： %s -> %s" % (image_id, image_url)
            self.saveCategoryImage(image_id, image_url)
            self.image_url_queue.task_done()
            #print '剩余' + str(self.image_url_queue.qsize())
            if (self.image_url_queue.empty()):
                print '结束'
                break
            
            